package com.suzhiliang.springbootlesson.javaMailDemo;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.List;
import java.util.Properties;

/**
 * Copyright (C), 2015-2018, XXX有限公司
 *
 * @ClassName: MailSender
 * @Author: xmm
 * @Date: 2018/10/18 16:52
 * @Description: 邮件发送者实体
 * @Version 1.0
 */
public class MailSender {

    private static MailEntity mailEntity = new MailEntity();

    /**
     * 设置邮件标题
     * @param title
     *     邮箱标题
     * @return
     */
    public MailSender title(String title){
        mailEntity.setTitle(title);
        return this;
    }

    /**
     * 设置邮件内容
     * @param content
     * @return
     */
    public  MailSender content(String content){
        mailEntity.setContent(content);
        return this;
    }

    /**
     * 设置邮件内容类型
     * @param contentTypeEnum
     * @return
     */
    public  MailSender contentType(MailContentTypeEnum contentTypeEnum){
        mailEntity.setContentType(contentTypeEnum.getValue());
        return this;
    }

    /**
     * 设置请求目标邮件地址列表
     * @param target
     * @return
     */
    public MailSender target(List<String> target){
        mailEntity.setToMailAdderList(target);
        return this;
    }

    /**
     * 执行发送文件
     * @throws Exception
     */
    public void sender() throws Exception{
        //默认按html格式发送
        if (mailEntity.getContentType()==null){
            mailEntity.setContentType(MailContentTypeEnum.HTML.getValue());
        }
        if (mailEntity.getTitle()==null || mailEntity.getTitle().trim().equals("")){
            throw new Exception("邮件标题未设置，请设置！");
        }
        if (mailEntity.getContent()==null || mailEntity.getContent().trim().equals("")){
            throw new Exception("邮件内容未设置，请设置！");
        }
        if (mailEntity.getToMailAdderList()==null || mailEntity.getToMailAdderList().isEmpty()){
            throw new Exception("没有接受邮件的地址，请设置！");
        }
        //读取mail.propertise 文件
        final PropertiesUtil propertiesUtil = new PropertiesUtil("mail");
        //创建propertise对象记录邮件信息
        final Properties properties = new Properties();
        //设置发送SMTP邮件必须验证
        properties.put("mail.smtp.auth",true);
        //设置SMTP服务器
        properties.put("mail.smtp.host",propertiesUtil.getValue("mail.smtp.service"));
        //设置发送SMTP邮件端口号（QQ邮箱给出465/587）
        properties.put("mail.smtp.port",propertiesUtil.getValue("mail.smtp.port"));
        //设置发送邮箱地址
        properties.put("mail.user",propertiesUtil.getValue("mail.from.address"));
        //设置发送邮箱的16位SMTP口令
        properties.put("mail.password",propertiesUtil.getValue("mail.from.pwd"));
        //构建授信信息，用于进行发送邮件身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected  PasswordAuthentication getPasswordAuthentication() {
                //用户名
                String userName = properties.getProperty("mail.user");
                String password = properties.getProperty("mail.password");

                return new PasswordAuthentication(userName,password);
            }
        };
        //使用环境信息和授权信息，创建邮件会话
        Session session = Session.getInstance(properties,authenticator);
        //创建邮件消息
        MimeMessage message = new MimeMessage(session);
        //设置发件人
        String nickName = MimeUtility.encodeText(propertiesUtil.getValue("mail.from.nickName"));
        InternetAddress from = new InternetAddress(nickName+"<"+properties.getProperty("mail.user")+">");
        message.setFrom(from);
        //设置发送标题
        message.setSubject(mailEntity.getTitle());
        //设置发送邮件格式和内容
        //HTML 格式发送
        if(mailEntity.getContentType().equals(MailContentTypeEnum.HTML.getValue())){
            //设置HTML邮件内容
            message.setContent(mailEntity.getContent(),mailEntity.getContentType());
        }else if(mailEntity.getContentType().equals(MailContentTypeEnum.TEXT.getValue())){
            //设置文本邮件内容
            message.setText(mailEntity.getContent());
        }

        //发送邮件地址
        List<String> targets = mailEntity.getToMailAdderList();

        InternetAddress to = null;
        for (String target:targets){
            try {
                //设置收件人邮件
                to = new InternetAddress(target);
                message.setRecipient(Message.RecipientType.TO,to);
                //最后发送邮件
                Transport.send(message);

            }catch (Exception e){
                e.printStackTrace();
                continue;
            }
        }


    }
}
